/*
 * DA2.c
 *
 * Created: 3/8/2015 9:55:31 AM
 *  Author: David Hunt
 */ 

//#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>

int main(void)
{
	int Count=0;
	DDRB = 0x30;							//Set portB.4 and 5 as output.
	DDRD = 0xFF;							//Set portD as output
			
	TCNT0 = 0xFB;							//Set count interrupt at 5//	TCCR0A |= (1<<WGM01);					//CTC mode on OCR0A
	TIMSK0 |= (1<< TOIE0);					//Set interrupt
	TCCR0B |= (1<<CS00)|(1<<CS01)|(1<<CS02);//Set counter0 to rising edge external signal

	sei();									//enable interrupts

	while(1)
	{	
		delay();					//rising clock delay call
		PORTB ^= 0x20;				//flip portB.5
		Count=Count+1;				//increase counter
		delay();					//falling clock delay call
		PORTB ^= 0x20;				//flip portB.5
		
		TCNT0=Count%5;				//interrupt error checking
		if (TCNT0==0)				//represents interrupt from counter0
			Interrupt();
		
		PORTD=Count;
	}
}
void delay()
{
	OCR1A = 0x0F42;							//set delay to .5 seconds
	TCCR1B |= (1 << WGM12);					//CTC mode on OCR1A
	TCCR1B |= (1 << CS12)|(1 << CS10);		//Set prescaler to 1024 and start timer

	while ((TIFR1&(1<<TOV1))>0)				//delay loop
	{
		TIFR1 &= ~(1 <<TOV1);				//reset flag after delay
	}
}

void Interrupt()
{
	PORTB ^=0x10;							//Toggle portB.4
}